package com.yeskery.nut.util.executor;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 组合任务步骤回调，用于组合多个回调方法
 * @author YESKERY
 * 2024/9/2
 */
public class ComposeJobStepCallback<T> implements JobStepCallback<T> {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(ComposeJobStepCallback.class.getName());

    /** 任务步骤回调方法集合 */
    private final List<JobStepCallback<T>> jobStepCallbacks = new ArrayList<>();

    /**
     * 构建组合任务步骤回调
     * @param jobStepCallbacks 任务步骤回调方法集合
     */
    public ComposeJobStepCallback(List<JobStepCallback<T>> jobStepCallbacks) {
        this.jobStepCallbacks.addAll(jobStepCallbacks);
    }

    /**
     * 添加任务步骤回调
     * @param jobStepCallback 任务步骤回调方法
     */
    public void addJobStepCallback(JobStepCallback<T> jobStepCallback) {
        jobStepCallbacks.add(jobStepCallback);
    }

    /**
     * 添加任务步骤回调集合
     * @param jobStepCallbacks 任务步骤回调方法集合
     */
    public void addJobStepCallbacks(List<JobStepCallback<T>> jobStepCallbacks) {
        this.jobStepCallbacks.addAll(jobStepCallbacks);
    }

    @Override
    public void callback(Job<T> job, JobStep<T> jobStep, T data, int index, RunResult runResult, ExecutorJobConfigure executorJobConfigure) {
        for (JobStepCallback<T> jobStepCallback : jobStepCallbacks) {
            try {
                jobStepCallback.callback(job, jobStep, data, index, runResult, executorJobConfigure);
            } catch (Exception e) {
                logger.log(Level.SEVERE, "JobStepCallback[" + jobStepCallback.getClass().getName() + "] Execute Fail.", e);
            }
        }
    }
}
